/*
 * ListenersLoader.cpp
 *
 *  Created on: Mar 16, 2009
 *      Author: Andrzej Olchawa
 *      mailto: andrzejolchawa@gmail.com
 *      http://www.hardtechnology.org
 *      This is a part of the Armazd project, which is covered by
 *      GNU GPL v2 license.
 */

#include "ListenersLoader.h"

ListenersLoader::ListenersLoader()
{
	listenersLocation = AgentConfiguration::getListenersConfigPath();
}

ListenersLoader::~ListenersLoader() {}

string ListenersLoader::getListenersLocation()
{
	return listenersLocation;
}

list<Listener*> *ListenersLoader::getListOfListeners()
{
	return listOfListeners;
}

void ListenersLoader::setListenersLocation(string path)
{
	listenersLocation = path;
}

list<Listener*> *ListenersLoader::setListOfListeners(list<Listener*> *listenersList)
{
	listOfListeners = listenersList;
	return listOfListeners;
}

list<Listener*> *ListenersLoader::loadListeners(list<Listener*> *listenersList)
{
	if (listenersList)
	{
		setListOfListeners(listenersList);
		try
		{
			loadListeners();
		}
		catch (AgentException &e)
		{
			e.printException();
		}
	}
	else
	{
		throw AgentException("list<Listener*> *ListenersLoader.loadListeners: listenersList is null");
	}
	return listOfListeners;
}

void ListenersLoader::loadListeners()
{
	HTProperties properties;
	try
	{
		properties.loadProperties(listenersLocation);
		for (int i=0; i<properties.getNumberOfElements(); i++)
		{
			string listenerName, listenerPath;
			int listenerPort, listenerType = -1;

			try
			{
				listenerName = properties[i].key;

				listenerType = AgentUtils::extractListenersInfoFromConfigLine(listenerPath,
						listenerPort, properties[i].value, i+1);
			}
			catch (AgentException &e)
			{
				e.printException();
			}
			catch (HTException &aoe)
			{
				aoe.printException();
			}

			if (listenerType == LISTENER_PORT)
			{
				Listener *listener = new ListenerPort(listenerName, listenerPort);
				listOfListeners->push_back(listener);
			}
			else if (listenerType == LISTENER_FILE)
			{
				Listener *listener = new ListenerFile(listenerName, listenerPath);
				listOfListeners->push_back(listener);
			}
		}
	}
	catch (HTException &aoe)
	{
		aoe.printException();
	}
}
